"""
消息相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.message import MessageResponse, MessageCreate
from app.schemas.common import ApiResponse, PageData
from app.models.message import Message
from app.models.user import User
from app.utils.helpers import generate_id

router = APIRouter()


@router.get("/list", response_model=ApiResponse[PageData[MessageResponse]])
async def get_message_list(
    type: Optional[str] = Query(None, pattern="^(booking|team|payment|system)$"),
    is_read: Optional[bool] = Query(None),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取消息列表
    """
    query = db.query(Message).filter(Message.user_id == current_user.id)
    
    # 筛选条件
    if type:
        query = query.filter(Message.type == type)
    if is_read is not None:
        query = query.filter(Message.is_read == is_read)
    
    # 按创建时间倒序
    query = query.order_by(Message.created_at.desc())
    
    # 分页
    total = query.count()
    messages = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    # 转换为响应格式
    message_list = [MessageResponse(**msg.to_dict()) for msg in messages]
    
    return ApiResponse(
        data=PageData(
            list=message_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/unread-count", response_model=ApiResponse[int])
async def get_unread_count(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取未读消息数量"""
    count = db.query(Message).filter(
        Message.user_id == current_user.id,
        Message.is_read == False
    ).count()
    
    return ApiResponse(data=count)


@router.post("/mark-read/{message_id}", response_model=ApiResponse[str])
async def mark_message_read(
    message_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """标记消息为已读"""
    message = db.query(Message).filter(
        Message.id == message_id,
        Message.user_id == current_user.id
    ).first()
    
    if not message:
        raise HTTPException(status_code=404, detail="消息不存在")
    
    message.is_read = True
    db.commit()
    
    return ApiResponse(data="标记成功")


@router.post("/mark-all-read", response_model=ApiResponse[str])
async def mark_all_read(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """标记所有消息为已读"""
    db.query(Message).filter(
        Message.user_id == current_user.id,
        Message.is_read == False
    ).update({"is_read": True})
    db.commit()
    
    return ApiResponse(data="标记成功")


@router.delete("/{message_id}", response_model=ApiResponse[str])
async def delete_message(
    message_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除消息"""
    message = db.query(Message).filter(
        Message.id == message_id,
        Message.user_id == current_user.id
    ).first()
    
    if not message:
        raise HTTPException(status_code=404, detail="消息不存在")
    
    db.delete(message)
    db.commit()
    
    return ApiResponse(data="删除成功")


# 系统消息创建接口（可选，供后台管理使用）
@router.post("/create", response_model=ApiResponse[MessageResponse])
async def create_message(
    message_data: MessageCreate,
    db: Session = Depends(get_db)
):
    """创建消息（供系统内部调用）"""
    message = Message(
        id=generate_id("msg"),
        user_id=message_data.userId,
        type=message_data.type,
        title=message_data.title,
        content=message_data.content,
        link=message_data.link,
        is_read=False
    )
    
    db.add(message)
    db.commit()
    db.refresh(message)
    
    return ApiResponse(data=MessageResponse(**message.to_dict()))

